package utils;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/1/10 16:09
 * @copyright: 博为峰
 */
public class DBUtils02 {
    private static DataSource dataSource = null;

    static {
        try {
            InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
            Properties properties = new Properties();
            properties.load(inputStream);

            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUrl(properties.getProperty("url"));
            druidDataSource.setUsername(properties.getProperty("username"));
            druidDataSource.setPassword(properties.getProperty("password"));
            //初始化连接数
            druidDataSource.setInitialSize(Integer.parseInt(properties.getProperty("initialSize")));
            //最大连接数
            druidDataSource.setMaxActive(Integer.parseInt(properties.getProperty("maxActive")));
            //数据源
            dataSource = druidDataSource;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //从数据源中获取数据库连接
    public static Connection getConn() throws SQLException {
        return dataSource.getConnection();
    }

    //关闭数据库连接(放到数据库连接池中)
    public static void closeConn(Connection conn) throws SQLException {
        conn.close();
    }
}
